package cn.lanqiao.springboot.util;

import cn.lanqiao.springboot.entity.Menu;
import cn.lanqiao.springboot.entity.Role;
import cn.lanqiao.springboot.service.MenuService;
import cn.lanqiao.springboot.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class CachePreLoad implements ApplicationRunner {

    @Autowired
    RoleService roleService;

    @Autowired
    MenuService menuService;

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<Role> roleList = roleService.selectAllRoles();
        for (Role role : roleList) {
            List<Menu> menuList = menuService.selectAllMenus(role.getRoleId());
            redisTemplate.opsForValue().set("menuList:" + role.getRoleId(), menuList);
        }
        log.debug("缓存预热完成");
    }
}
